import React, { useState, useEffect } from 'react';
import { Card, Typography, Spin, Button, message, DatePicker, Select, Space } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { API_CONFIG } from '../../config';
import styles from './index.module.less';
import { Link } from 'react-router-dom';

const { Title } = Typography;
const { Option } = Select;

interface LogFile {
  date: string;
  label: string;
}

const LogPage: React.FC = () => {
  const [logs, setLogs] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(true);
  const [logFiles, setLogFiles] = useState<LogFile[]>([]);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [loadingFiles, setLoadingFiles] = useState<boolean>(true);

  // 获取可用的日志文件列表
  const fetchLogFiles = async () => {
    setLoadingFiles(true);
    try {
      const response = await fetch(`${API_CONFIG.BASE_URL}/logs/list`);
      if (!response.ok) {
        throw new Error('获取日志列表失败');
      }
      const data = await response.json();
      
      // 格式化日志文件列表
      const formattedLogs = data.logs.map((dateStr: string) => ({
        date: dateStr,
        label: `${dateStr} 日志`
      }));
      
      setLogFiles(formattedLogs);
      
      // 如果有日志文件且没有选择日期，默认选择第一个（最新的）
      if (formattedLogs.length > 0 && !selectedDate) {
        setSelectedDate(formattedLogs[0].date);
      }
    } catch (error) {
      console.error('获取日志列表时出错:', error);
      message.error('获取日志列表失败，请稍后重试');
    } finally {
      setLoadingFiles(false);
    }
  };

  // 获取特定日期的日志
  const fetchLogs = async (date?: string) => {
    setLoading(true);
    try {
      const url = date 
        ? `${API_CONFIG.BASE_URL}/logs?date=${date}`
        : `${API_CONFIG.BASE_URL}/logs`;
        
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('获取日志失败');
      }
      const data = await response.text();
      setLogs(data);
    } catch (error) {
      console.error('获取日志时出错:', error);
      message.error('获取日志失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载时获取日志文件列表
  useEffect(() => {
    fetchLogFiles();
  }, []);

  // 当选择的日期变化时，获取对应的日志
  useEffect(() => {
    if (selectedDate) {
      fetchLogs(selectedDate);
    }
  }, [selectedDate]);

  // 处理日期选择变化
  const handleDateChange = (value: string) => {
    setSelectedDate(value);
  };

  // 刷新日志
  const handleRefresh = () => {
    fetchLogs(selectedDate || undefined);
  };

  return (
    <div className={styles.logPageContainer}>
      <Card 
        title={
          <div className={styles.cardTitle}>
            <Title level={3}>服务器日志</Title>
            <Space>
              <Select
                placeholder="选择日期查看日志"
                style={{ width: 200 }}
                value={selectedDate}
                onChange={handleDateChange}
                loading={loadingFiles}
              >
                {logFiles.map(file => (
                  <Option key={file.date} value={file.date}>
                    {file.label}
                  </Option>
                ))}
              </Select>
              <Button 
                type="primary" 
                icon={<ReloadOutlined />} 
                onClick={handleRefresh}
                loading={loading}
              >
                刷新日志
              </Button>
              <Link to="/main">
                            <Button 
                type="primary" 
                icon={<ReloadOutlined />} 
                loading={loading}
              >
                返回渲染页
              </Button>
              </Link>

            </Space>
          </div>
        }
        className={styles.logCard}
      >
        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" />
            <p>正在加载日志...</p>
          </div>
        ) : (
          <div className={styles.logContent}>
            <pre>{logs || '暂无日志'}</pre>
          </div>
        )}
      </Card>
    </div>
  );
};

export default LogPage; 